package landx.toolkit.display 
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import landx.toolkit.utils.StringUtil;
	
	/**
	 * ...
	 * @author nease@163.com
	 * Ini加载解析类
	 */
	[Event(name = "complete", type = "flash.events.Event")]
	[Event(name = "ioError", type = "flash.events.IOErrorEvent")]
	public class KeyPairLoader extends EventDispatcher 
	{
		private var m_table:Dictionary;
		private var m_path:String;
		public function KeyPairLoader(request:URLRequest=null) 
		{
			if (request != null) {
				load(request);
			}
		}
		
		/**
		 * 加载Ini配置文件
		 * @param	request
		 */
		public function load(request:URLRequest):void {
			m_path = request.url;
			var loader:URLLoader = new URLLoader(request);
			loader.addEventListener(Event.COMPLETE, successHandle);
			loader.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent);
		}
		
		/**
		 * 成功后调用
		 * @param	event
		 */
		private function successHandle(event:Event):void {
			var loader:URLLoader = event.target as URLLoader;
			var text:String = loader.data;
			m_table = new Dictionary();
			//切割text
			var lines:Array = text.split("\n");
			for (var i:int = 0; i < lines.length; i++ ) {
				fillLine(lines[i]);
			}
			this.dispatchEvent(event);
		}
		
		/**
		 * 填充数据表
		 * @param	text
		 */
		private function fillLine(text:String):void {
			var line:String = text.split("\r").join("");
			var pairIndex:int = line.indexOf("=");
			if (pairIndex > 0) {
				var key:String = line.substring(0, pairIndex);
				var value:String = line.substring(pairIndex + 1, line.length);
				//去空格
				write(key,value);
			}
		}
		
		/**
		 * 读取指定的键值
		 * @param	key
		 * @return	读取的结果
		 */
		public function read(key:String):String {
			if (m_table[key] != undefined) {
				return m_table[key];
			}
			return null;
		}
		
		/**
		 * 写入指定的键值，如果value="" 则删除该键值
		 * @param	key
		 * @param	value
		 */
		public function write(key:String, value:String):void {
			if (!StringUtil.isNullOrEmpty(key)) {
				if (!StringUtil.isNullOrEmpty(value)) {
					m_table[key] = value;
				}else {
					del(key);
				}
			}
		}
		
		/**
		 * 删除指定的key
		 * @param	key	删除的key
		 * @return	删除是否成功
		 */
		public function del(key:String):Boolean {
			if (m_table[key] != undefined) {
				delete m_table[key];
				return true;
			}
			return false;
		}
		
		/**
		 * 获取配置路径
		 */
		public function get Path():String {
			return m_path;
		}
	}

}